<template>
  <div class="login">
    <!-- 在查询登录状态时显示loading -->
    <!-- <div v-if="isLoading" class="loading-mask d-flex flex-center">
      <van-loading size="24px" vertical>加载中...</van-loading>
    </div> -->
    <div class="bg"></div>
    <div class="head">
      <div class="head__title">Hello!</div>
      <div class="head__subtitle">{{ $tv('login.subTitle1', headerTitle) }}</div>
    </div>
    <div class="form">
      <div class="form-title">{{ $tv('login.formTitle1', '验证码登录') }}</div>

      <van-field
        v-model.trim="form.mobile"
        :border="false"
        type="number"
        :placeholder="$tv('login.mobilePlaceholder', '请输入手机号')"
        center
        maxlength="11"
        @focus="onFieldFocus"
      />
      <van-field
        v-model.trim="form.validationCode"
        :border="false"
        :placeholder="$tv('login.verifyPlaceholder', '请输入验证码')"
        center
        maxlength="6"
        type="number"
        @focus="onFieldFocus"
      >
        <template #button>
          <div class="get-verify-btn">
            <van-button
              round
              type="primary"
              class="verify-btn"
              block
              :disabled="verifyDisabled"
              size="small"
              @click.stop="getVerifyCode"
            >
              <van-count-down v-if="verifyDisabled" :time="60000" @finish="verifyDisabled = false">
                <template #default="timeData">
                  <span class="shades--text text--white">{{ timeData.seconds }}s</span>
                </template>
              </van-count-down>
              <span v-else class="shades--text text--white">{{ vcodeTip }}</span>
            </van-button>
          </div>
        </template>
      </van-field>

      <div class="form-submit">
        <van-button
          block
          round
          size="large"
          :disabled="submitDisabled"
          type="primary"
          :loading="loading"
          @click="submit"
        >
          {{ $tv('login.btnText1', '登录') }}
        </van-button>
      </div>
    </div>
    <div class="protocol">
      <van-checkbox v-model="acceptProtocol">
        <!-- this.$siteConfig.primary -->
        <span>{{ $tv('login.acceptProtocol', '我已认真阅读并同意') }}</span>
        <span @click.stop="getPdf('userProtocal')">{{ $tv('login.protocol1', '《用户服务协议》') }}</span>
        <span @click.stop="getPdf('privacyPolicy')">{{ $tv('login.protocol2', '《隐私权政策》') }}</span>
      </van-checkbox>
    </div>
    <div class="footer">
      <div class="company-logo" :style="{ backgroundImage: `url(${logo})` }"></div>
    </div>
    <van-overlay :show="isMask" :lock-scroll="false">
      <div class="overlay-wrapper" @click.stop>
        <div class="overlay-block">
          <div id="pdfViewer"></div>
          <van-submit-bar button-text="关闭">
            <template #button>
              <van-button style="width: 100px" type="primary" round size="small" @click="isMask = false"
                >关闭</van-button
              >
            </template>
          </van-submit-bar>
        </div>
      </div>
    </van-overlay>
    <van-dialog v-model="acceptProtocolModalShow" title="服务协议及隐私政策" :show-confirm-button="false">
      <div class="dialog">
        用户，你好！<br />为了更好地保障您的合法权益，请您阅读并同意以下协议
        <span @click.stop="getPdf('userProtocal')">{{ $tv('login.protocol1', '《用户服务协议》') }}</span>
        <span @click.stop="getPdf('privacyPolicy')">{{ $tv('login.protocol2', '《隐私权政策》') }}</span>
        <div class="dialog-footer">
          <div class="dialog-footer-btn mr-2">
            <van-button plain type="primary" block round size="small" @click="acceptProtocolModalShow = false"
              >不同意</van-button
            >
          </div>
          <div class="dialog-footer-btn">
            <van-button type="primary" block round size="small" @click="acceptProtocolModalOk">同意</van-button>
          </div>
        </div>
      </div>
    </van-dialog>
  </div>
</template>
<router>
{
  path:'/login',
  meta:{anonymous:true},
}
</router>
<script>
import { getOSSBaseUrl } from '@/utils/index.js';
import { setUserToken } from '@/api/utils/submit-token';
import Pdfh5 from 'pdfh5';
import * as PDFNames from '@/assets/pdf';

export default {
  name: 'Login',
  head() {
    const title = this.$tv('login.pageTitle1', '登录');
    return {
      title,
    };
  },
  data() {
    return {
      form: {
        mobile: '',
        validationCode: '',
      },
      acceptProtocol: false,
      acceptProtocolModalShow: false,
      logo: getOSSBaseUrl(this.$siteConfig.profile?.logo),
      verifyDisabled: false,
      vcodeTip: this.$tv('login.getVerifyText', '获取验证码'),
      headerTitle: '欢迎进入健康管理平台',
      isMask: false, // pdf遮罩
      pdfh5: null,
      loading: false,
    };
  },
  computed: {
    submitDisabled() {
      return !this.form.mobile || this.form.validationCode.length !== 6;
    },
  },
  methods: {
    acceptProtocolModalOk() {
      this.acceptProtocolModalShow = false;
      this.acceptProtocol = true;
      this.submit();
    },
    // 获取pdf
    getPdf(name) {
      this.isMask = true;
      if (!name || !PDFNames[name]) {
        return this.$toast('缺少必要参数 name');
      }

      this.pdfh5 = new Pdfh5('#pdfViewer', {
        pdfurl: PDFNames[name],
      });

      this.pdfh5.on('complete', function (status, msg, time) {
        // eslint-disable-next-line no-console
        console.log('状态：' + status + '，信息：' + msg + '，耗时：' + time + '毫秒，总页数：' + this.totalNum);
      });
    },
    // 获取验证码
    async getVerifyCode() {
      if (!/^1[3-9][0-9]{9}$/.test(this.form.mobile)) return this.$toast('请输入正确手机号');
      const data = {
        scene: 6,
        mobile: this.form.mobile,
      };
      await this.$$healthApis.mobileValidationCode({ data, dataType: 'default' });
      this.verifyDisabled = true;
      this.$toast('验证码已发送，请注意查收');
      this.vcodeTip = this.$tv('login.getVerifyText', '重新获取');
    },
    // 登录
    submit() {
      if (!this.acceptProtocol) {
        this.acceptProtocolModalShow = true;
        return;
      }
      this.loading = true;
      const data = {
        grant_type: 'password',
        scope: 'all',
        client_id: 'lejian-client',
        client_secret: 'lejian-client',
        login_type: 'validationCode',
        username: this.form.mobile,
        password: this.form.validationCode,
      };
      this.$$loginApis
        .loginByMobile({ data, dataType: 'default', catchError: false, loading: true })
        .then((res) => {
          if (res.access_token) {
            setUserToken(res.access_token);
            this.goTo(this.$route.query.next || { name: 'home' });
          }
        })
        .catch((err) => {
          this.$dialog.alert({
            title: '系统提示',
            message: err.message || '登录失败',
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    onFieldFocus() {
      // ios微信网页，键盘弹出页面会错位
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: 'smooth',
      });
    },
  },
};
</script>
<style>
@import 'pdfh5/css/pdfh5.css';
#pdfViewer {
  height: 100vh;
}
</style>
<style lang="less" scoped>
.van-overlay {
  z-index: 9999;
}
.loading-mask {
  position: fixed;
  background-color: #fff;
  z-index: 1000;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}

.login {
  position: relative;
  padding: 30px 24px;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  background-color: @white;
  &::v-deep {
    .get-verify-btn {
      .van-button {
        padding: 11px 13px;
      }
    }
    .van-field {
      background-color: @gray-2;
      border-radius: 25px;
      padding: 18px unset 18px unset;
      height: 50px;
      box-sizing: border-box;
      margin-bottom: 15px;
      &__control {
        font-size: 14px;
        color: @gray-8;
        font-weight: 600;
        line-height: 14px;
        &::placeholder {
          font-weight: 400 !important;
          color: @gray-6 !important;
        }
      }
    }

    .van-checkbox {
      align-items: center;
      text-align: left;
      &__icon {
        font-size: 12px;
        line-height: 12px;
        .van-icon {
          line-height: unset;
        }
      }
      &__label {
        margin-left: 5px;
      }
    }
  }

  .verify-btn {
    width: 100px;
  }

  .bg {
    width: 100%;
    height: 210px;
    border-radius: 0 0 50px 50px;
    background-color: @primary-color;
    position: absolute;
    top: 0;
    left: 0;
  }
}

.head {
  height: 80px;
  overflow: hidden;

  &__title {
    margin-bottom: 11px;
    font-size: 25px;
    font-weight: bold;
    color: @white;
    line-height: 25px;
    position: relative;
  }
  &__subtitle {
    font-size: 14px;
    font-weight: 400;
    color: @white;
    line-height: 14px;
    position: relative;
  }
}

.form {
  height: 275px;
  background-color: @white;
  box-shadow: 0px 0px 15px 0px fade(@gray-5, 40%);
  border-radius: 10px;
  padding: 40px 28px;
  box-sizing: border-box;
  position: relative;

  &-title {
    font-size: 25px;
    font-weight: 500;
    color: @gray-8;
    line-height: 25px;
    margin-bottom: 28px;
  }

  &-submit {
    position: absolute;
    bottom: -25px;
    width: 100%;
    left: 0;
    padding: 0 28px;
    box-sizing: border-box;
  }
}
.protocol {
  padding-left: 14px;
  margin-top: 38px;
  font-size: 12px;
  line-height: 12px;
  span {
    &:first-child {
      color: @gray-6;
    }
    &:not(:first-child) {
      color: @primary-color;
    }
  }
}
.dialog {
  padding: 20px;
  position: relative;
  font-size: 12px;
  color: @gray-8;
  line-height: 24px;
  > span {
    color: @primary-color;
    cursor: pointer;
  }
  &-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;
    &-btn {
      width: 143px;
    }
  }
}
.footer {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  text-align: center;

  .company-logo {
    width: 100px;
    height: 80px;
    margin: 10px auto;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
  }
}

.overlay-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.overlay-block {
  width: 100%;
  height: 100%;
  background-color: #fff;
}
</style>
